<template>
  <div class="app-container tz-app">


    <div class="zt-select flex-s">
      <div class="flex-left">
        <el-select v-model="queryParams.radioStationName" filterable placeholder="电台名称" class="zt-input rihgt-m5">
          <!-- <el-option v-for="item in options" :key="item.label" :label="item.label" :value="item.label">
          </el-option> -->
        </el-select>

        <el-select v-model="queryParams.sensorName" filterable placeholder="传感器" class="zt-input-min rihgt-m5">
          <el-option v-for="item in  dict.type.sensor_type" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <button class="bt-blue " @click="handleQuery">筛选</button>

      </div>

    </div>






    <div class="tz-table-box" style="height:calc(100vh - 250px);">
      <el-table v-loading="loading" :data="sensorList" @selection-change="handleSelectionChange"
        height="calc(100vh - 250px)" class="zt-table">
        <el-table-column label="传感器ID" align="center" prop="sensorId" />
        <el-table-column label="传感器名称" align="center" prop="sensorName">
          <template slot-scope="scope">
            <div :class="{ 'red': scope.row.isNet == 0 }">{{ scope.row.sensorName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="150" />
        <el-table-column label="传感器类型" align="center" prop="sensorType">
          <template slot-scope="scope">
            {{ getSensorType(scope.row.sensorType) }}
          </template>
        </el-table-column>
        <el-table-column label="所属地址" align="center" prop="locatedAddress">
          <template slot-scope="scope">
            {{ getLocatedAddress(scope.row.locatedAddress) }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="使用状态" align="center" prop="isUsed" /> -->
        <!-- <el-table-column label="传感器属性" align="center" prop="sensorAttribute" /> -->
        <el-table-column label="所属节点" align="center" prop="status">
          <template slot-scope="scope">-</template>
        </el-table-column>
        <el-table-column label="所属机房" align="center" prop="status">
          <template slot-scope="scope">-</template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <div>{{ scope.row.status == 0 ? '正常' : '异常' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="入网状态" align="center" prop="isNet">
          <template slot-scope="scope">
            <div :class="{ 'red': scope.row.isNet == 0 }">{{ scope.row.isNet == 0 ? '未入网' : '已入网' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:sensor:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:sensor:remove']">删除</el-button> -->

            <img src="@/assets/images/amend.png" style="width: 20px;height: 20px;cursor: pointer;margin-top: 10px; margin-right: 20px;"
              @click="handleUpdate(scope.row)" />
            <img src="@/assets/images/delete-bin2.png" style="width: 20px;height: 20px;cursor: pointer;margin-top: 10px; margin-right: 20px;"
              @click="handleDelete(scope.row)" />

            <el-popover placement="top-start" popper-class="zt-popper" width="200" trigger="click" 
              @after-enter="sensorAttributeOpen(scope.row.sensorAttribute)" @hide="sensorAttributeClose">
              <template #reference>
                <img src="@/assets/images/xs.png" style="width: 20px;height: 20px;margin-top: 10px; cursor: pointer;">
              </template>
              <template v-show="popoverOpen" #default>
                <div class="flex">
                  <div>
                    <div v-for="(item, index) in sensorAttribute" :key="index" style="color: #25CAD5;">
                      {{ item.name }}:{{ item.value }}
                    </div>
                  </div>
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />



    <right-dialog :title="title" :visible="open" @closeDialog="cancel">
      <template v-slot:default>
        <div class="zt-dialog-solt">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="传感器名称:" prop="sensorName">
              <div class="flex">
                <el-input class="blue-input" v-model="form.sensorName" placeholder="请输入传感器名称" />
                <el-button class="bt-blue " @click="submitForm" style="margin-left: 10px; ">{{ title == '添加天线' ? '添加' :
                  '确定'
                }}</el-button>
              </div>
            </el-form-item>
            <el-form-item label="传感器类型:">
              <div class="flex">
                <el-select v-model="form.sensorType" filterable placeholder="传感器类型" class="zt-input-min rihgt-m5">
                  <el-option v-for="item in  dict.type.sensor_type" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
                <div style="margin-right: 5px; width: 60px; text-align: right;font-weight: 600;">所属地:
                </div>
                <el-select v-model="form.locatedAddress" filterable placeholder="所属地" class="zt-input-min rihgt-m5"
                  style="width: 120px;font-weight: 600;">
                  <el-option v-for="item in  dict.type.located_address" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
                <div v-if="isNet == 0" style=";margin-right: 5px; width: 90px; text-align: right;">入网状态:</div>
                <el-select v-if="isNet == 0" v-model="form.isNet" filterable placeholder="入网状态"
                  class="zt-input-min rihgt-m5">
                  <el-option key="0" label="未入网" value="0" />
                  <el-option key="1" label="已入网" value="1" />
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="备注:" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>

        </div>
      </template>
    </right-dialog>


  </div>
</template>

<script>
import { listSensor, getSensor, delSensor, addSensor, updateSensor } from "@/api/business/sensor";
import RightDialog from "@/components/TZ/RightDialog"
export default {
  name: "Sensor",
  components: { RightDialog },
  dicts: ['located_address', 'sensor_type', 'sensor_code'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 传感器表格数据
      sensorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sensorName: null,
        sensorType: null,
        sensorAttribute: null,
        status: null,
      },
      arr: [
        { "name": "W湿度", "value": 62.9 }, { "name": "N温度", "value": 8.3 }, { "name": "N湿度", "value": 61.5 },
        { "name": "风速", "value": 60 }, { "name": "风向", "value": '西北风' }, { "name": "雨量", "value": 61.5 },
        { "name": "W温度", "value": 90 }, { "name": "风力", "value": '100' }
      ],
      arrs: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sensorName: [
          { required: true, message: "传感器名称不能为空", trigger: "blur" }
        ],
        sensorType: [
          { required: true, message: "传感器类型不能为空", trigger: "change" }
        ],
        sensorAttribute: [
          { required: true, message: "传感器属性不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      },
      isNet: null,
      sensorAttribute: {},
      popoverOpen: false,
    };
  },
  created() {
    this.getList();
  },
  methods: {

    sensorAttributeClose() {//清除传感器属性
      this.sensorAttribute = {};
      this.popoverOpen = false;
    },
    sensorAttributeOpen(data) {//显示传感器属性

      this.sensorAttribute = this.parseJsonString(data);
      this.popoverOpen = true;
      console.log(this.sensorAttribute);
    },

    /** 查询传感器列表 */
    getList() {
      this.loading = true;
      listSensor(this.queryParams).then(response => {
        this.sensorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //将字符串解析成对象
    parseJsonString(jsonString) {
      // console.log(jsonString);
      const string = JSON.parse(jsonString);
      const sensorCodeArray = this.dict.type.sensor_code;
      console.log(JSON.stringify(sensorCodeArray));
      const resultArray = sensorCodeArray
        .filter(sensor => string.hasOwnProperty(sensor.value))
        .map(sensor => ({ name: sensor.label, value: parseInt(string[sensor.value]) / 10 }));

      // console.log(JSON.stringify(resultArray));

      // const arr = [
      //   {"name":"W湿度","value":62.9},{"name":"N温度","value":8.3},{"name":"N湿度","value":61.5},
      //   {"name":"风速","value":60},{"name":"风向","value":'西北风'},{"name":"雨量","value":61.5},
      //   {"name":"W温度","value":80},{"name":"风力","value":'100'}
      // ]

      // const arrs = [
      //   {"name":"室外湿度","value":"62.9Pa","type":0},{"name":"室内温度","value":"88.3℃","type":1},{"name":"室内湿度","value":"61.Pa","type":0},
      //   {"name":"风速","value":"60m/s","type":0},{"name":"风向","value":'西北风',"type":0},{"name":"雨量","value":"61.5mm","type":0},
      //   {"name":"室外温度","value":"70℃","type":0},{"name":"风力","value":'100级',"type":0}
      // ]

      // 将arr数组转为arrs数组，w表示室外，n表示室内，温度的单位是℃，雨量的单位是mm，湿度的单位是Pa，风力的单位是级...type的值为0表示正常，当温度大于80的时候为异常type的值应该为1



      return this.transformArray(resultArray);

    },
    transformArray(resultArray) {


      return resultArray.map(item => {
        let newItem = { name: '', value: '', type: 0 };

        // Set name and value
        if (item.name.includes('W')) {
          newItem.name = '室外' + item.name.substring(1);
        } else if (item.name.includes('N')) {
          newItem.name = '室内' + item.name.substring(1);
        } else {
          newItem.name = item.name;
        }

        newItem.value = item.value;

        // Set type based on conditions
        if ((item.name.includes('温度') && item.value > 80) || (item.name === '雨量' && item.value > 0)) {
          newItem.type = 1; // 异常
        }

        // Add units based on name
        if (item.name.includes('温度')) {
          newItem.value += '℃';
        } else if (item.name.includes('湿度')) {
          newItem.value += 'Pa';
        } else if (item.name.includes('风速')) {
          newItem.value += 'm/s';
        } else if (item.name.includes('风力')) {
          newItem.value += '级';
        } else if (item.name === '雨量') {
          newItem.value += 'mm';
        }

        return newItem;
      });


    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sensorId: null,
        sensorName: null,
        sensorType: null,
        sensorAttribute: null,
        locatedAddress: null,
        isNet: null,
        isUsed: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sensorId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加传感器";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sensorId = row.sensorId || this.ids
      getSensor(sensorId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改传感器";
        this.isNet = this.form.isNet;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sensorId != null) {
            updateSensor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSensor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sensorIds = row.sensorId || this.ids;
      this.$modal.confirm('是否确认删除传感器编号为"' + sensorIds + '"的数据项？').then(function () {
        return delSensor(sensorIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/sensor/export', {
        ...this.queryParams
      }, `sensor_${new Date().getTime()}.xlsx`)
    },
    getLocatedAddress(index) {
      const entries = this.dict.type.located_address;
      for (let i = 0; i < entries.length; i++) {
        if (entries[i].value == index) {
          return entries[i].label
        }
      }
      return ""
    },
    getSensorType(index) {
      const entries = this.dict.type.sensor_type;
      for (let i = 0; i < entries.length; i++) {
        if (entries[i].value == index) {
          return entries[i].label
        }
      }
      return ""
    }
  }
};
</script>
